﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Common
{
    /// <summary>
    /// jwt工具类
    /// <para>不是静态类 可以依赖注入进ioc容器</para>
    /// </summary>
    public class JwtHelper
        (IConfiguration configuration)
    {
        /// <summary>
        /// 生成token
        /// 
        /// </summary>
        /// <param name="claims">用户权限信息</param>
        /// <returns>token字符串</returns>
        public string CreateToken(Claim[]? claims )
        {
       

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"]!));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                configuration["Jwt:Issuer"],     //Issuer
                configuration["Jwt:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
               DateTime.Now.AddDays(1),    //expires
                signingCredentials               //Credentials
            );

            // 6. 将token变为string
            var token = new JwtSecurityTokenHandler()
                                    .WriteToken(jwtSecurityToken);

            return token;
        }

        /// <summary>
        /// 从请求头的token获取payload
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public  Dictionary<string, string> GetClaims(HttpRequest Request, params string[] keys)
        {
            Dictionary<string, string> dc = [];
            try
            {
                string token = Request.Headers.Authorization[0]
                                ?.Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
                                .Trim();
                var handler = new JwtSecurityTokenHandler();
                var payload = handler.ReadJwtToken(token).Payload;
                var claims = payload.Claims;
           
              
                foreach (var key in keys)
                {
                    Claim? claim = claims.FirstOrDefault(c => c.Type.Equals( key));
                    if (claim is null) continue;
                    dc.Add(key, claim.Value);
                }
                return dc;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return dc;
            }
        }

    }
}
